package net.wangds.yunz.initialize.flow;

import net.wangds.yunz.auth.comp.AuthAccountComp;
import net.wangds.common.base.funcs.Functions;
import net.wangds.jpa.Sorts;
import net.wangds.log.helper.LogHelper;
import net.wangds.procengine.ProcResEnum;
import net.wangds.procengine.flow.FlowContext;
import net.wangds.procengine.flow.define.FlowDef;
import net.wangds.procengine.flow.define.actor.ActorDef;
import net.wangds.procengine.flow.define.node.FlowNode;
import net.wangds.procengine.flow.define.node.JavaFlowNode;
import net.wangds.procengine.flow.instance.actor.Actor;
import net.wangds.program.auth.module.AuthAccount;
import net.wangds.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.function.BiFunction;

/**
 * .
 * <p></p>
 *
 * @author 王东石 2020/10/18 14:59.
 */
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class StepInitAccount extends JavaFlowNode {

    public static final String KEY_ACCOUNTS = "ACCOUNTS";

    @Autowired
    private AuthAccountComp mmCmpAccount;


    public <A extends ActorDef> StepInitAccount(FlowDef<A> flow,
                                                     FlowNode previousNode) {
        super(flow, previousNode);
        this.setFunc(this::proc);
    }

    public <A extends ActorDef> StepInitAccount(FlowDef<A> flow,
                                                     BiFunction<FlowContext, Actor, ProcResEnum> func,
                                                     FlowNode previousNode) {
        super(flow, func, previousNode);
    }

    private ProcResEnum proc(FlowContext ctx, Actor actor) {

        LogHelper.dev("清理账户");
        //删除现有应用
        mmCmpAccount.findAll().forEach(c->mmCmpAccount.erase(c));

        LogHelper.dev("初始化现有应用");

        //BCryptPasswordEncoder encoder = SpringUtils.getBean(BCryptPasswordEncoder.class);

        Functions.ofList(
                AuthAccount.ofNewUser("admin", "123456", "", "管理员", "管理员", "", "", "")
        ).stream().peek(c-> c.setPassword(Md5Utils.md5(c.getPassword())))
                .forEach(mmCmpAccount::save);
        ctx.putBean(KEY_ACCOUNTS, mmCmpAccount.findAll(Sorts.createTm_asc));

        return ProcResEnum.CONTINUE;
    }
}